import { defineStore } from "pinia";
import { store } from "@/store";
import { getDecryptMessage, getEncryptionMessage, websoctkeTypes } from "@/config/websoctke";
import type { WebSocketProps, dataToSend, reqServiceMessage, sendFace } from "@/config/websoctke";
import { ElMessage } from "element-plus";
import { getMitt } from "@/utils/mitt";

const appStore = defineStore({
    id: "websoctke",
    state: (): WebSocketProps => ({
        url: "",
        reconnectCount: 0,
        webSocket: undefined,
        setIntervalId: null,
        falg: false,
        reconnectId: null,
        heartTime: 350000,
        heartMsg: "ping",
        reconnectTime: 1000,
        socket_id: '',
    }),

    getters: {
        getSocketId(): string {
            return this.socket_id
        }
    },
    actions: {
        initWebSocket(url: string) {
            if (url) {
                this.url = url
            }
            if (typeof WebSocket === "undefined") {
                ElMessage.error(
                    "您的浏览器不支持Websocket通信协议，请使用Chrome或者其他高版本的浏览器！"
                );
                return;
            }
            if (
                this.webSocket != null &&
                this.webSocket.readyState === this.webSocket.OPEN
            ) {
                return this.webSocket;
            }
            this.createWebSocket();
            return this.webSocket;
        },
        /**
         * 创建WebSocket
         * @param config
         */
        createWebSocket() {
            // 初始化 WebSocket
            this.webSocket = new WebSocket(this.url);
            this.webSocket.onopen = (ev: Event) => {
                console.log("接受到信息===>", ev);

                /**
                 * 发送心跳
                 * 使用Nginx代理WebSocket的时候，客户端与服务器握手成功后，如果在60秒内没有数据交互，就会自动断开连接。
                 * Nginx默认的断开链接时间为60秒
                 */
                // this.sendPing(this.heartTime, this.heartMsg);
            };
            this.webSocket.onmessage = (ev: MessageEvent) => this.message(ev);
            this.webSocket.onerror = (ev: Event) => this.error(ev);
            this.webSocket.onclose = (ev: CloseEvent) => this.close(ev);
        },
        /**
         * 发送心跳
         * @param {number} heartTime 心跳间隔毫秒 默认50000
         * @param {string} heartMsg 心跳名称 默认字符串ping
         */
        sendPing() {
            const data: sendFace = {
                type: websoctkeTypes.MessageTypeHeartbeat,
                account_uuid: "",
                data: ""
            }
            this.sendMessages(data)

        },
        sendMessages(data: sendFace) {
            try {
                const d1 = JSON.stringify(data)
                const d = getEncryptionMessage(d1)
                this.webSocket?.send(JSON.stringify(d));
            } catch (error) {
                console.error("sendMessages不能转换为json")
            }


        },
        /**
         * WebSocket 关闭的回调方法
         * @param config
         */
        close(e: Event) {
            clearInterval(Number(this.setIntervalId));
        },
        /**
         * WebSocket 关闭的回调方法
         * @param config
         */
        error(ev: Event) {
            console.log(ev)
            if (this.falg) return;
            this.reconnectId = setInterval(() => {
                this.falg = true;
                this.reconnectCount++;
                console.log("正在重新连接，次数：" + this.reconnectCount);
                let socket = this.initWebSocket();
                if (socket?.readyState === socket?.OPEN) {
                    this.reconnectCount = 0;
                    this.falg = false;
                    clearInterval(Number(this.reconnectId));
                }
                if (this.reconnectCount >= 5) {
                    clearInterval(Number(this.reconnectId));
                }
            }, this.reconnectTime);
        },
        message(ev: MessageEvent<any>) {
            const slef = this
            const s = JSON.parse(ev.data) as dataToSend
            const msg = getDecryptMessage(s)
            if (msg == "") {
                return
            }
            const data = JSON.parse(msg) as reqServiceMessage
            console.log("接受到信息", data)
            const mitt = getMitt()
            if (data.data) {
                const d = JSON.parse(data.data) as sendFace
                const sendType = d.type

                mitt.emit(`${sendType}`, data.body)

            } else {
                switch (data.type) {
                    case websoctkeTypes.MessageTypeHeartbeat:
                        this.sendPing()
                        break;
                    case websoctkeTypes.MessageTypeRegister:
                        const socket_id = data.body.data || ""
                        slef.setSocketId(socket_id)
                        break;
                    case websoctkeTypes.NotificationMessage:
                        mitt.emit(`${websoctkeTypes.NotificationMessage}`, data.body)
                        break;
                    case websoctkeTypes.SysHi:
                        mitt.emit(`${websoctkeTypes.NotificationMessage}`, data.body)
                        break;
                    default:
                        break;
                }
            }

        },
        setSocketId(s: string) {
            this.socket_id = s
        }
    },
});
export function useWebsoctkeStoreWithOut() {
    return appStore(store);
}
